<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="角色名称">
            <el-input v-model="formInline.roleName" placeholder="请输入角色名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button type="primary" @click="openAddDialog" v-if="isAdmin">新增角色</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-main>
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="roleName" label="角色名称" width="150" />
          <el-table-column prop="description" label="角色描述" width="200" />
          <el-table-column label="权限列表" width="300">
            <template #default="scope">
              <el-tag v-for="perm in scope.row.permissions" :key="perm" size="small" effect="plain">
                {{ perm }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="scope">
              <el-button type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
              <el-button type="danger" @click="handleDelete(scope.row)" v-if="isAdmin">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 新增/编辑角色弹窗 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑角色' : '新增角色'" width="600px">
          <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="formData.roleName" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="角色描述" prop="description">
              <el-input v-model="formData.description" placeholder="请输入角色描述" />
            </el-form-item>
            <el-form-item label="权限配置" prop="permissions">
              <el-select v-model="formData.permissions" multiple placeholder="请选择权限">
                <el-option label="客户管理" value="client:manage" />
                <el-option label="供应商管理" value="supplier:manage" />
                <el-option label="角色管理" value="role:manage" />
                <el-option label="质检管理" value="quality:manage" />
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确认</el-button>
          </template>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { useCounterStore } from '@/stores/counter';

// 状态管理
const pinia = useCounterStore();
const isAdmin = pinia.piniaDto.roleName === '管理员';

// 筛选表单
const formInline = reactive({
  roleName: ''
});

// 表格数据 - 本地模拟数据
const tableData = ref([
  {
    id: 1,
    roleName: '管理员',
    description: '系统最高权限管理员',
    permissions: ['client:manage', 'supplier:manage', 'role:manage', 'quality:manage']
  },
  {
    id: 2,
    roleName: '质检人员',
    description: '负责质检相关工作',
    permissions: ['quality:manage']
  },
  {
    id: 3,
    roleName: '客户专员',
    description: '负责客户管理工作',
    permissions: ['client:manage']
  }
]);

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();
const formData = reactive({
  id: 0,
  roleName: '',
  description: '',
  permissions: [] as string[]
});

// 表单校验规则
const rules = reactive({
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  permissions: [{ required: true, message: '请选择至少一个权限', trigger: 'change' }]
});

// 页面初始化
onMounted(() => {
  // 初始加载数据
});

// 查询角色列表
const onSubmit = () => {
  // 本地筛选逻辑
  const filterText = formInline.roleName.toLowerCase();
  if (!filterText) {
    // 恢复原始数据
    loadDefaultData();
    return;
  }
  
  // 简单本地筛选
  const filtered = tableData.value.filter(item => 
    item.roleName.toLowerCase().includes(filterText)
  );
  tableData.value = filtered;
};

// 加载默认数据
const loadDefaultData = () => {
  // 恢复默认数据
  tableData.value = [
    {
      id: 1,
      roleName: '管理员',
      description: '系统最高权限管理员',
      permissions: ['client:manage', 'supplier:manage', 'role:manage', 'quality:manage']
    },
    {
      id: 2,
      roleName: '质检人员',
      description: '负责质检相关工作',
      permissions: ['quality:manage']
    },
    {
      id: 3,
      roleName: '客户专员',
      description: '负责客户管理工作',
      permissions: ['client:manage']
    }
  ];
};

// 打开弹窗
const openAddDialog = () => {
  isEdit.value = false;
  formData.id = 0;
  formData.roleName = '';
  formData.description = '';
  formData.permissions = [];
  dialogVisible.value = true;
};

const openEditDialog = (row: any) => {
  isEdit.value = true;
  formData.id = row.id;
  formData.roleName = row.roleName;
  formData.description = row.description;
  formData.permissions = [...row.permissions];
  dialogVisible.value = true;
};

// 提交表单
const submitForm = () => {
  if (!formRef.value) return;
  
  formRef.value.validate(valid => {
    if (valid) {
      if (isEdit.value) {
        // 编辑操作 - 本地更新
        const index = tableData.value.findIndex(item => item.id === formData.id);
        if (index !== -1) {
          tableData.value[index] = { ...formData };
          ElMessage.success('角色更新成功');
        }
      } else {
        // 新增操作 - 本地添加
        const newId = Math.max(...tableData.value.map(item => item.id)) + 1;
        tableData.value.push({ ...formData, id: newId });
        ElMessage.success('角色新增成功');
      }
      dialogVisible.value = false;
    }
  });
};

// 删除角色
const handleDelete = (row: any) => {
  // 防止删除管理员角色
  if (row.roleName === '管理员') {
    ElMessage.warning('不能删除管理员角色');
    return;
  }
  
  ElMessageBox.confirm(
    `确认删除角色"${row.roleName}"吗？`,
    '删除确认',
    { type: 'warning' }
  ).then(() => {
    // 本地删除
    tableData.value = tableData.value.filter(item => item.id !== row.id);
    ElMessage.success('角色删除成功');
  });
};
</script>

<style scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.el-header {
  padding: 16px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e5e7eb;
}

.el-main {
  padding: 16px;
}

.el-table {
  margin-bottom: 16px;
}
</style>
